package com.lancoo.ccas53.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: mabolin
 * @Date: 2024-08-27-17:44
 * @Description:
 */
@Service
@Slf4j
public class DistributedLockService {
    @Resource
    private RedissonClient redissonClient;

    public DistributedLockService(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    // 获取分布式锁，并在执行完毕后自动释放锁
    public void doWithLock(String lockKey, Runnable action) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 尝试获取锁，最多等待 10 秒，锁的自动释放时间设置为 30 秒
            if (lock.tryLock(10, 30, TimeUnit.SECONDS)) {
                // 获取锁成功，执行业务逻辑
                action.run();
            } else {
                // 获取锁失败，处理并发冲突
                log.warn(lockKey + "获取锁失败");
            }
        } catch (InterruptedException e) {
            // 处理异常
            log.error("获取锁失败，处理并发冲突", e);
        } finally {
            //判断要解锁的key是否已被锁定;判断要解锁的key是否被当前线程持有
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
